<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2019/9/2
 * Time: 15:46
 */

namespace app\plat\controller;


use think\Cookie;
use think\Db;

class Site extends Base
{
    public $table = 'site';
    public function __construct()
    {
        parent::__construct();
    }


    public function index()
    {
        $keyword = input('keyword');
        if($keyword){
            $where['name'] = ['like','%'.$keyword.'%'];
        }
        if(!isset($where))
            $where = '1=1';

        $data['list'] = Db::name($this->table)
            ->alias('a')
            ->where($where)
            ->order('a.id desc')

            ->paginate();
        $data['page'] = $data['list']->render();

        $this->assign('data',$data);
        $this->assign('keyword',$keyword);

        return $this->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            return $this->save();
        }
        $this->assign('data',1);
        $this->assign('title','新增');
        $this->assign('url',url('add'));
        return $this->fetch('info');
    }

    public function update()
    {
        $id = input('id/d');
        $data = Db::name($this->table)->where('id',$id)->find();
        if(!$data){
            $this->error('不存在');
        }
        if(request()->isPost()){
            return $this->save();
        }
        $this->assign('data',json_encode($data));
        $this->assign('title','编辑');
        $this->assign('url',url('update'));
        return $this->fetch('info');
    }

    public function save()
    {
        $id = input('id/d');
        $param = input();
        $data = [
            'name'=>input('name'),
            'enable'=>input('enable/d'),
            'link_name'=>input('link_name'),
            'link_tel'=>input('link_tel'),
            'modtime'=>time(),
        ];
        if($id){
            $a = Db::name($this->table)->where('id',$id)->update($data);
        }else{
            $data['addtime'] = time();
            $data['open'] = 0;
            $a = Db::name($this->table)->insert($data);
        }
        if($a){
            echo api_return(1,'保存成功');
        }else{
            echo api_return(0,'保存失败');
        }
        return;
    }

    public function enter_site_admin()
    {
        $site_id = input('site_id');
        $site = Db::name($this->table)->where('id',$site_id)->find();
        if(!$site){
            $this->error('站点不存在');
        }
        $user = Db::name('site_user')->where('site_id',$site_id)->where('is_super',1)->find();
        if(!$user)
            $this->error('请先创建该站点登录账号');
        $domain = request()->domain();

        session('admin',$user);

        $this->redirect($domain.'/admin');
    }

    public function getConfig()
    {
        $config['template'] = Db::name('template')->order('id desc')->select();
        $this->assign('config',json_encode($config,JSON_UNESCAPED_UNICODE));
        return $config;
    }
}